package com.example.viewtest.gesture_12;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.example.viewtest.R;
import com.example.viewtest.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自己绘制自己的 多点触控
 */
public class AloneGestureView extends View {

    private Paint paint;

    private List<PointF> points;

    public AloneGestureView(Context context) {
        this(context, null);
    }

    public AloneGestureView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AloneGestureView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStrokeWidth(Utils.db2px(30));
        points = new ArrayList<>();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int masked = event.getActionMasked();
        switch (masked) {
            case MotionEvent.ACTION_DOWN:
                points.add(new PointF(event.getX(), event.getY()));
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                int downIndex = event.getActionIndex();
                points.add(new PointF(event.getX(downIndex), event.getY(downIndex)));
                break;
            case MotionEvent.ACTION_POINTER_UP:
                int upIndex = event.getActionIndex();
                points.remove(upIndex);
                break;
            case MotionEvent.ACTION_MOVE:
                for (int i = 0; i < points.size(); i++) {
                    points.get(i).set(event.getX(i), event.getY(i));
                }
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                points.remove(0);
                invalidate();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (points.size() > 0) {
            for (PointF point : points) {
                canvas.drawPoint(point.x, point.y, paint);
            }

        }
    }
}
